#ifndef _M_CLOUD
#define _M_CLOUD
#include "data.hpp"
//#define SRV_IP "8.137.48.24"
#define SRV_IP "127.0.0.1"
#define SRV_PORT 9090
#include "httplib.h"
namespace tqbcloud {
	class BackUp {
	private:
		tqbcloud::DataManager* _data;
		std::string _back_dir;
		std::string _back_file;
	public:
		BackUp(const std::string& back_dir, const std::string& back_file)
			: _back_dir(back_dir)
			, _back_file(back_file) {
			_data = new tqbcloud::DataManager(back_file);
		}
		std::string GetFileIdentifier(const std::string& filename) {
			tqbcloud::Fileutil fu(filename);
			std::stringstream ss;
			ss << fu.FileName() << "-" << fu.FileSize() << "-" << fu.Lastmotime();
			return ss.str();
		}
		bool Upload(const std::string& filename) {
			std::string body;
			tqbcloud::Fileutil fu(filename);
			fu.GetContent(&body);
			httplib::Client client(SRV_IP, SRV_PORT);
			httplib::MultipartFormData item;
			item.filename = fu.FileName();
			item.name = "file";
			item.content = body;
			//item.content_type = "application/octet-stream;charset=utf-8";
			//item.content_type = "application/x-www-form-urlencoded";
			item.content_type = "application/octet-stream;charset=utf-8";
			httplib::MultipartFormDataItems items;
			items.push_back(item);
			/*httplib::Headers headers = {
			{ "Content-Type", "multipart/form-data" }
			};*/
			//auto ret = client.Post("/upload", headers ,items);

			auto ret = client.Post("/upload", items);
			if (!ret || ret->status != 200) {
				return false;
			}
			return true;
		}
		bool IsCanBeUpload(const std::string& filename) {
			std::string val;
			if (_data->GetOneByKey(filename, &val) == false) {//无记录
				return true;
			}
			else {//有记录
				tqbcloud::Fileutil fu(filename);
				if (val != GetFileIdentifier(filename)) {
					if (time(NULL) - fu.Lastmotime() < 5) {//有记录但是跟上次更改间隔过短 防止大文件写入时间过长 造成多次上传
						
						return false;
					}
					return true;
				}
				else {//有记录且没有被更改
					return false;
				}
			}
		}
		bool RunModule() {
			tqbcloud::Fileutil fu(_back_dir);
			if (!fu.Exists()) {
				fu.CreateDirectory_();
			}
			while (1) {
				std::vector<std::string> arry;
				fu.ScanDirectory(&arry);
				for (auto& i : arry) {
					if (IsCanBeUpload(i) == false) {
						continue;
					}
					if (Upload(i) == true) {
						_data->Insert(i, GetFileIdentifier(i));
						std::cout << i << ":�ύ�ɹ�" << std::endl;
					}
					else {
						std::cout << i << ":�ύʧ��" << std::endl;
					}
				}
			}
		}
	};
}

#endif

